<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>视频转码</title>

    <link rel="stylesheet" href="/bootstrap/dist/css/bootstrap.min.css" />

    <script src="/custom/js/jquery.min.js"></script>
    <script src="/bootstrap/dist/js/bootstrap.min.js"></script>

    <style>

        #table_data{
            padding: 2% 10%;
        }
        #search_data{
            padding-bottom: 20px;
        }

        .float-left{
            float: left;
        }

        .modal-body{
            height: 150px;
        }

    </style>


</head>
<body>


    <div id="table_data" >
        <h1>视频转码</h1>
        <div id="search_data">

            <!--<button class="btn btn-primary" data-toggle="modal" data-target="#myModal">添加视频</button>-->

        </div>
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <td>编号</td>
                    <td>名称</td>
                    <td>创建时间</td>
                    <td>状态</td>
                    <td>操作</td>
                </tr>
            </thead>
            <tbody>

                <% for(var i = 0; i < tbody_data.length; i ++){ %>
                   <tr>
                       <td><%=parseInt(i) + 1 %></td>
                       <td><%=tbody_data[i].name %></td>
                       <td><%=formatDateTime(tbody_data[i].createDate) %></td>
                       <td>
                           <% if(tbody_data[i].status == 1){ %> 等待转码
                           <% }else if(tbody_data[i].status == 2){ %> 转码中
                           <% }else if(tbody_data[i].status == 3){ %> 转码成功
                           <% }else if(tbody_data[i].status == 4){ %> 上传成功
                           <% }%>
                       </td>

                       <td>
                           <% if(tbody_data[i].status == 3){ %>
                           <a href="/download/<%=tbody_data[i]._id%>">下载转码视频</a>
                           <%}%>
                       </td>
                   </tr>
                <% } %>


            </tbody>
        </table>
    </div>

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">添加转码视频</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" onsubmit="return false">
                        <div class="form-group">
                            <label for="name" class="col-sm-2 control-label">名称</label>
                            <div class="col-sm-8">
                                <input type="text" name="name" class="form-control" id="name" placeholder="输入视频名称">
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-10 col-sm-offset-2">
                                <button id="uploadVideoButton" type="button" class="btn btn-default col-sm-3" onclick="ClickUploadButton();">上传视频</button>

                                <div id="process_bar" class="col-sm-5 hidden" style="margin-top: -15px">
                                    <h5><span id="uploadStateText">上传中</span> <span id="process_bar_percent_1">0%</span></h5>
                                    <div class="progress progress-sm">
                                        <div class="progress-bar progress-bar-indicating progress-bar-success active" id="process_bar_percent_2" style="width: 0%;" role="progressbar"></div>
                                    </div>
                                    <input class="hidden" type="text" name="file_url" value="" />
                                </div>
                            </div>
                        </div>
                    </form>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="tijiaoButton();">提交</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

    <script>

        $('#myModal').on('hidden.bs.modal', function (e) {
            console.log("模态对对话框消失")
        });
        
        
        function tijiaoButton() {
            var file_url = $("input[name='file_url']").val();   // 视频链接
            var name = $("#name").val();    // 名称

            var data = {
                "file_url": file_url,
                "name": name
            };

            $.ajax({
                type: "POST",
                url: "/create/",
                data: JSON.stringify(data),
                dataType: "json",
                contentType:'application/json',
                success: function (result) {
                    alert(result["message"]);
                    if(result["status"]){
                        console.log("提交成功");
                        $('#myModal').modal('hide');

                        window.location.reload();

                    }else{

                        console.log(result);

                    }

                }
            });


        }



        const BYTES_PER_CHUNK = 10 * 1024 * 1024;   // 每次上传1Mb
        var slices;
        var totalSlices;


        // 点击上传视频按钮
        function ClickUploadButton() {
            // 将 input 标签的内容清空
            $("input[name='file_url']").val('');

            // 创建上传文件的 input 标签
            var input = document.createElement('input');
            input.setAttribute("type", "file");
            input.setAttribute("class", "hidden");
            input.setAttribute("id", "uploadVideoInput");
            input.setAttribute("accept", "video/*");
            var uploadVideoButton = document.getElementById("uploadVideoButton");
            uploadVideoButton.parentNode.appendChild(input);

            // 当选择完文件后执行回调函数
            input.onchange = function () {

                var blob = input.files[0];
                var start = 0;
                var end;
                var index = 0;

                // 计算文件切片总数
                slices = Math.ceil(blob.size / BYTES_PER_CHUNK);
                totalSlices= slices;

                while(start < blob.size) {
                    $("#process_bar").removeClass("hidden");
                    end = start + BYTES_PER_CHUNK;
                    if(end > blob.size) {
                        end = blob.size;
                    }

                    uploadFile(blob, index, start, end);

                    start = end;
                    index++;
                }
            };

            input.click();
        }


        // 设置上传文件进度条百分比
        function setPercent(percent) {

            var uploadStateText = $("#uploadStateText");
            var process_bar_percent_1 = $("#process_bar_percent_1");
            var process_bar_percent_2 = $("#process_bar_percent_2");

            if(percent == 100){
                uploadStateText.html("上传成功");
                process_bar_percent_2.removeClass("progress-bar-indicating");

            }else{
                uploadStateText.html("上传中");
                process_bar_percent_2.addClass("progress-bar-indicating");
            }

            percent = percent.toString() + "%";
            process_bar_percent_1.html(percent);
            process_bar_percent_2.css("width", percent);
        }

        //上传文件
        function uploadFile(blob, index, start, end) {
            var xhr;
            var fd;
            var chunk;

            chunk = blob.slice(start,end);//切割文件

            //构造form数据
            fd = new FormData();
            fd.append("file", chunk);
            fd.append("name", blob.name);
            fd.append("index", index);

            $.ajax({
                type: "POST",
                url: "/uploadVideo/",
                data: fd,
                dataType: "json",
                processData: false,
                contentType: false,
                success: function (result) {
                    if(result["status"]){

                        var percent = parseInt((totalSlices - slices) / totalSlices * 100);
                        setPercent(percent);

                        slices--;
                        if(slices == 0){mergeFile(blob)}
                    }
                }
            });
        }

        // 发起合并请求
        function mergeFile(blob) {
            var xhr;
            var fd;

            fd = new FormData();
            fd.append("name", blob.name);
            fd.append("index", totalSlices);

            $.ajax({
                type: "POST",
                url: "/mergeVideo/",
                data: fd,
                dataType: "json",
                processData: false,
                contentType: false,
                success: function (result) {
                    if(result["status"]){
                        setPercent(100);
                        $("input[name='file_url']").val(result["file_url"])
                    }
                }
            });
        }
    </script>
</body>
</html>